use std::error::Error;
use std::fs;

pub struct Config {
    pub remove_start: usize,
    pub remove_end: usize,
    pub filename: String,
}

impl Config {
    pub fn new(remove_start: String, remove_end: String, filename: String) -> Result<Config, &'static str> {
        let remove_start: usize = remove_start.trim().parse().unwrap_or_else(|_e| 0);
        let remove_end: usize = remove_end.trim().parse().unwrap_or_else(|_e| 0);
        println!("删除{}单位头部\r\n删除{}单位尾部", remove_start, remove_end);
        Ok(Config { remove_start, remove_end, filename })
    }

    pub fn run(self) -> Result<String, Box<dyn Error>> {
        let contents = fs::read_to_string(self.filename)?;
        let results = excel(&contents);
        let mut str = String::new();
        for line in results {
            if self.remove_start + self.remove_end > line.len() {
                eprint!("err:首尾过长！");
                str.push_str("首尾过长！");
                break
            }
            let l = &line.replace(",", "");
            str.push_str("'");
            str.push_str(&l[self.remove_start..l.len() - self.remove_end]);
            str.push_str("',");
        }
        println!("{}", &str);
        fs::write("out.txt", &str).expect("!");
        // println!("文本：\r\n{}", contents);
        Ok(str)
    }
}

pub fn excel(contents: &str) -> Vec<&str> {
    contents.lines().collect()
}